<!DOCTYPE html>
<html>

<head>
    <!-- 在一个div内拖拽元素，小地图效果 -->
    <meta charset="utf-8">
    <title>在一个div内拖拽元素</title>
    <style>
        #dv {
            width: 100px;
            height: 100px;
            border: 1px solid #a9a9a9;
            opacity: 0.4;
            background-color: rgb(79, 111, 126);
            box-sizing: border-box;
            position: absolute;
            transition: all 0.1s;
            border-radius: 2px;
        }

        .container {
            width: 300px;
            height: 300px;
            background-color: whitesmoke;
            position: relative;
            margin: 50px auto;
            border-radius: 2px;

        }
    </style>
</head>

<body>


    <div id="con" class="container">
        <div id="dv"></div>
    </div>




</body>

</html>

<script>
    //获取元素
    var dv = document.getElementById('dv');
    var x = 0;
    var y = 0;
    var l = 0;
    var t = 0;
    var isDown = false;
    //鼠标按下事件
    dv.onmousedown = function (e) {
        //获取x坐标和y坐标
        x = e.clientX;
        y = e.clientY;

        //获取左部和顶部的偏移量
        l = dv.offsetLeft;
        t = dv.offsetTop;
        //开关打开
        isDown = true;
        //设置样式  
        dv.style.cursor = 'move';
    }


    // con.onmousemove = function (e) {


    //     if (isDown == false) {
    //         return;
    //     }

    //     console.log(e);

    // }

    // 鼠标移动
    con.onmousemove = function (e) {

        // const { x, clientX, layerX, movementX, offsetX, pageX, screenX } = e;

        // console.log({ x, clientX, layerX, movementX, offsetX, pageX, screenX });


        if (isDown == false) {
            return;
        }

        // console.log({x, y, l, t});

        //获取x和y
        var nx = e.clientX;
        var ny = e.clientY;
        //计算移动后的左偏移量和顶部的偏移量
        var nl = nx - (x - l);
        var nt = ny - (y - t);

        if (nl < 0) {
            nl = 0;
        }

        if (nl > 200) {
            nl = 200;
        }

        dv.style.left = nl + 'px';

        if (nt < 0) {
            nt = 0;
        }

        if (nt > 200) {
            nt = 200;
        }

        dv.style.top = nt + 'px';
    }
    //鼠标抬起事件
    con.onmouseup = function () {
        //开关关闭
        isDown = false;
        dv.style.cursor = 'default';
    }

    window.onmouseup = function () {
        //开关关闭
        isDown = false;
        dv.style.cursor = 'default';
    }

</script>